#pragma once

#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<cstring>
#include<string>

using namespace std;

enum{
    SocketErr = 2,
    BindErr,
    ListenErr,
    AcceptErr,
};


extern Log lg;


const int backlog = 10;


class Sock
{
public:
    Sock()
    {}
    ~Sock()
    {}
public:

    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_sockfd < 0)
        {
            lg(Fatal, "socket error, %s:%d\n", strerror(errno), errno);
            exit(SocketErr);
        }
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if(bind(_sockfd, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, %s:%d\n", strerror(errno), errno);
            exit(SocketErr);
        }
    }

    void Listen()
    {
        if(listen(_sockfd, backlog) < 0)
        {
            lg(Fatal, "listen error, %s:%d\n", strerror(errno), errno);
            exit(ListenErr);
        }
    }

    int Accept(string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int newfd = accept(_sockfd, (struct sockaddr*)&peer, &len);
        if(newfd < 0)
        {
            lg(Warning, "accept error, %s:%d\n", strerror(errno), errno);
            return AcceptErr;
        }
        *clientport = (ntohs)(peer.sin_port);
        char ipstr[64];
        inet_ntop(AF_INET, &peer.sin_addr, ipstr, sizeof(ipstr));
        *clientip = ipstr;
        return newfd;
    }
    
    int Connet()
    {
        
    }

    void Close()
    {
        close(_sockfd);
    }
private:
    int _sockfd;
};